package com.chuan.icons;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

/* Base class of sites. */
public class SiteBase {
	public String mUser;
	public String mSite;
	public FriendActivity mFAContext = null;

	SiteBase(FriendActivity context) {
		mFAContext = context;
	}

	public void getInfo() {
		;
	}

	public static SiteBase getSiteClass(String sitename, FriendActivity context) {
		if (sitename.equals("renren")) {
			return new Renren(context);
		} else if (sitename.equals("douban")) {
			return new Douban(context);
		} else if (sitename.equals("twitter")) {
			return new Twitter(context);
		}
		return null;
	}

	public JSONArray getAccountInfo() {
		return null;
	}

	public Boolean pairFriends(JSONObject info) {
		return false;
	}

	public Boolean getFriendsList(JSONObject info) {
		return false;
	}

	public static byte[] urlDownload(String url) {
		URL target_url;
		int len;
		try {
			target_url = new URL(url);
		} catch (MalformedURLException e1) {
			Log.e(Constants.LOG_FLAG, "URL error.");
			return null;
		}

		byte[] buf = null;
		HttpURLConnection http;
		InputStream in;
		try {
			http = (HttpURLConnection) target_url.openConnection();
			http.setDoInput(true);
			http.setConnectTimeout(10000);
			http.setRequestMethod("GET");
			http.setRequestProperty("accept", "*/*");
			http.connect();
			in = http.getInputStream();
			len = http.getContentLength();
			if (len < 0) {
				return null;
			}
			buf = new byte[len];

			if ((in.read(buf)) == -1) {
				return null;
			}

			in.close();
		} catch (IOException e) {
			return null;
		} catch (Exception e) {
			return null;
		}

		return buf;
	}

	public Boolean addFriends(String f_id, String name, String icon) {
		JSONObject parameter = new JSONObject();
		try {
			parameter.put("f_id", f_id);
			parameter.put("name", name);
			parameter.put("icon", icon);
		} catch (JSONException e) {
			return false;
		}

		if (name != null && f_id != null && icon != null) {
			if (LiteDB.addFriends(f_id, mUser, mSite, parameter) < 0) {
				Log.e(Constants.LOG_FLAG, "Add fail: " + name + " " + " "
						+ f_id + " " + icon);
				return false;
			}
		}
		return true;
	}

	public static String httpDownload(String url) {
		URL target_url;
		try {
			target_url = new URL(url);
		} catch (MalformedURLException e1) {
			return null;
		}

		HttpURLConnection conn;
		StringBuffer buffer = new StringBuffer();
		try {
			conn = (HttpURLConnection) target_url.openConnection();
			conn.connect();
			BufferedReader br = new BufferedReader(new InputStreamReader(conn
					.getInputStream()));
			String line;

			while ((line = br.readLine()) != null) {
				buffer.append(line);
			}

			br.close();
		} catch (IOException e) {
			Log.e(Constants.LOG_FLAG, "Download fail.", e);
			return null;
		} catch (Exception e) {
			Log.e(Constants.LOG_FLAG, "Download fail.", e);
			return null;
		}

		return buffer.toString();
	}

	public static String basicAuthDownload(String url, String user, String pass) {
		String basicstr = user + ":" + pass;
		URL target_url;
		try {
			target_url = new URL(url);
		} catch (MalformedURLException e1) {
			return null;
		}

		HttpURLConnection conn;
		StringBuffer buffer = new StringBuffer();
		try {
			conn = (HttpURLConnection) target_url.openConnection();
			conn.setRequestProperty("Authorization", "Basic "
					+ Base64.encodeToString(basicstr.getBytes(), false));
			conn.connect();
			BufferedReader br = new BufferedReader(new InputStreamReader(conn
					.getInputStream()));
			String line;

			while ((line = br.readLine()) != null) {
				buffer.append(line);
			}

			br.close();
		} catch (IOException e) {
			Log.e(Constants.LOG_FLAG, "Download fail.", e);
			return null;
		} catch (Exception e) {
			Log.e(Constants.LOG_FLAG, "Download fail.", e);
			return null;
		}

		return buffer.toString();
	}

	public Boolean pairFriendsByName(JSONObject info) {
		String user, site;
		try {
			user = info.getString("user");
			site = info.getString("site");
		} catch (JSONException e) {
			return false;
		}

		JSONArray friends = LiteDB.getFriends(user, site);

		PairedType pair_type = new PairedType();
		pair_type.type = Constants.UNKNOWN_TYPE;

		Log.d(Constants.LOG_FLAG, "Pair friends Start.");
		for (int i = 0; i < friends.length(); ++i) {
			try {
				ArrayList<Integer> retval = Common.pairContactByName(friends
						.getJSONObject(i).getJSONObject("parameter").getString(
								"name"), pair_type);
				if (retval != null) {
					for (int ti = 0; ti < retval.size(); ++ti) {
						if (LiteDB.addRelationship(user, site, friends
								.getJSONObject(i).getString("f_id"), retval
								.get(ti).intValue(), pair_type.type) == -1) {
							Log.e(Constants.LOG_FLAG, "Add relationship fail.");
						}
					}
				} else {
					if (LiteDB.addRelationship(user, site, friends
							.getJSONObject(i).getString("f_id"), -1,
							pair_type.type) == -1) {
						Log.e(Constants.LOG_FLAG, "Add relationship fail.");
					}
				}
			} catch (JSONException e) {
				continue;
			}
		}

		Log.d(Constants.LOG_FLAG, "Pair friends End.");

		return true;
	}

	public class PairedType {
		public Integer type = -1;
	}

	public void updateDiagInfo(String msg) {
		if (mFAContext == null) {
			return;
		}
		mFAContext.sendSetDialogMsg(msg);
	}

	public void updateDiagInfo(int id) {
		if (mFAContext == null) {
			return;
		}
		mFAContext.sendSetDialogMsg(mFAContext.getResources().getString(id));
	}
}
